package com.zlx.store.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zlx.store.domain.doc.GoodsDoc;
import com.zlx.store.domain.entity.Goods;
import com.zlx.store.domain.vo.GoodsVo;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.SimpleQueryStringBuilder;
import com.zlx.store.goods.dao.GoodDocDao;
import com.zlx.store.goods.dao.GoodsCategoryDao;
import com.zlx.store.goods.dao.GoodsDao;
import com.zlx.store.goods.dao.StoreDao;
import com.zlx.store.goods.service.GoodDocService;
import org.apache.ibatis.annotations.Mapper;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.print.Book;
import java.io.IOException;
import java.util.*;

@Service
public class GoodDocServiceImpl implements GoodDocService {

    @Autowired
    private GoodDocDao goodDocDao;
    @Autowired
    private GoodsDao goodDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public void update() throws IOException {
        //删除数据
        GetIndexRequest request = new GetIndexRequest("goods_doc");
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        if (exists) {
            DeleteIndexRequest deleteRequest = new DeleteIndexRequest("goods_doc");
            restHighLevelClient.indices().delete(deleteRequest, RequestOptions.DEFAULT);
        }
        //增添数据
        LambdaQueryWrapper<Goods> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Goods::getGoodsSaleState,1);
        wrapper.gt(Goods::getGoodsStock,0);
        wrapper.and(w -> w.gt(Goods::getGoodsExpirationTime, new Date()).or().isNull(Goods::getGoodsExpirationTime));
        List<Goods> goods=goodDao.selectList(wrapper);
        goods.forEach(
                good -> {
                    String goodStore=(String) redisTemplate.opsForHash().get("category",String.valueOf(good.getGoodsCategory()));
                    String goodCate=(String) redisTemplate.opsForHash().get("store",String.valueOf(good.getGoodsStoreId()));
                    goodDocDao.save(new GoodsDoc().build(good,goodCate,goodStore));
                });
    }

    @Override
    public HashMap<String,Object> search(String keyword,String order,String store,String category,Integer pageNum,Integer pageSize) throws IOException {
        List<GoodsDoc> list=new ArrayList();
        SearchRequest searchRequest=new SearchRequest("goods_doc");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //查询字段
        if (keyword!=null) {
            SimpleQueryStringBuilder simpleQueryStringQuery = QueryBuilders.simpleQueryStringQuery(keyword);
            searchSourceBuilder.query(simpleQueryStringQuery);
        }
        else {
            MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
            searchSourceBuilder.query(matchAllQueryBuilder);
        }
        //店铺
        if (store!=null){
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("goodsStore", store);
            searchSourceBuilder.query(termQueryBuilder);
        }
        //分类
        if (category!=null) {
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("goodsCategory", category);
            searchSourceBuilder.query(termQueryBuilder);
        }
        //排序
        if(order!=null){
            searchSourceBuilder.sort(order, SortOrder.DESC);
        }
        //分页
        searchSourceBuilder.from(pageNum);
        searchSourceBuilder.size(pageSize);


        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse=restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        SearchHit[] hits = searchResponse.getHits().getHits();
        int length=hits.length;
        // 获取total总数
        Long total = searchResponse.getHits().getTotalHits().value;
        List<GoodsDoc> goodsList = new ArrayList<>();
        //获取查询到的商品
        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            String goodsId = hit.getId();
            String goodsName = (String) sourceAsMap.get("goodsName");
            String goodsSku = (String) sourceAsMap.get("goodsSku");
            String goodsPic = (String) sourceAsMap.get("goodsPic");
            String goodsDescription = (String) sourceAsMap.get("goodsDescription");
            Double goodsPrice = (Double) sourceAsMap.get("goodsPrice");
            Integer goodsForNewcomer = (Integer) sourceAsMap.get("goodsForNewcomer");
            Integer goodsSales = (Integer) sourceAsMap.get("goodsSales");
            Double goodsDiscount = (Double) sourceAsMap.get("goodsDiscount");
            String goodsCategory = (String) sourceAsMap.get("goodsCategory");
            String goodsStore = (String) sourceAsMap.get("goodsStore");
            GoodsDoc goodsDoc=new GoodsDoc(goodsId,goodsName,goodsSku,goodsPic,goodsDescription,goodsPrice,goodsForNewcomer,goodsSales,goodsDiscount,goodsCategory,goodsStore);
            goodsList.add(goodsDoc);
        }

// 将查询结果封装到map中返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("data", goodsList);
        return map;
    }
}
